// components/index-home/unit-entry/index.js
const { categoryConfig } = require('../../../utils/categoryConfig');
// 获取全局app实例
const app = getApp();

Component({
  properties: {},
  data: {
    wordbooks: [],
    cachedWordbooksData: null,
    cacheExpireTime: null,
    isLoading: false
  },
  lifetimes: {
    attached() {
      // 设置加载状态
      this.setData({ isLoading: true });
      
      // 使用setTimeout实现延迟加载，避免阻塞页面渲染
      setTimeout(() => {
        this.loadUserData();
        this.setData({ isLoading: false });
      }, 50);
    }
  },
  methods: {
    openWordbook(e) {
      const wordbookId = e.currentTarget.dataset.id;
      const wordbook = this.data.wordbooks.find(book => book.id === wordbookId);
      
      wx.navigateTo({
        url: `/pages/vocabulary/word-list/word-list?category=${encodeURIComponent(wordbook.category)}`
      });
    },
    
    // 获取分类的实际单词数量
    getCategoryWordCount(category) {
      try {
        // 使用app中的全局实例
        const dm = app.getWordDataManager();
        const words = dm.getWordsByCategory(category);
        return words.length;
      } catch (error) {
        console.error(`获取分类单词数量失败 (${category}):`, error);
        return 0;
      }
    },
    
    // 获取分类中已学习的单词数量
    getLearnedWordCount(category) {
      try {
        // 使用app中的全局实例
        const dm = app.getWordDataManager();
        const words = dm.getWordsByCategory(category);
        
        // 统计已学习的单词数量（learnCount > 0 表示已学习）
        const learnedCount = words.filter(word => {
          return dm.getWordLearnedStatus(word.id);
        }).length;
        
        return learnedCount;
      } catch (error) {
        console.error(`获取分类已学习单词数量失败 (${category}):`, error);
        return 0;
      }
    },
    
    // 加载用户学习数据
    loadUserData() {
      try {
        // 检查是否有缓存且未过期
        const now = Date.now();
        const cacheDuration = 3 * 60 * 1000; // 增加缓存时间到3分钟
        
        if (this.data.cachedWordbooksData !== null && 
            this.data.cacheExpireTime !== null && 
            now < this.data.cacheExpireTime) {
          // 使用缓存数据
          this.setData({ wordbooks: this.data.cachedWordbooksData });
          return;
        }
        
        // 性能优化：一次性获取所有需要的数据，避免重复读取本地存储
        const dm = app.getWordDataManager();
        const allWords = dm.getAllWords();
        const wordsArray = Object.values(allWords);
        
        // 基于共享的分类配置创建词书数据并计算学习进度
        // 优化：在内存中一次性处理所有数据，避免多次调用存储API
        const updatedWordbooks = categoryConfig.map(category => {
          try {
            // 过滤出该分类的单词
            const categoryWords = wordsArray.filter(word => 
              word.categories && word.categories.includes(category.category)
            );
            
            // 获取该分类的实际单词数量
            const actualWordCount = categoryWords.length;
            
            // 获取该分类的已学习单词数量（一次遍历完成）
            const learnedCount = categoryWords.filter(word => {
              return dm.getWordLearnedStatus(word.id);
            }).length;
            
            // 计算进度百分比
            const progress = actualWordCount > 0 ? Math.round((learnedCount / actualWordCount) * 100) : 0;
            
            return {
              id: category.id.toString(),
              name: category.name || category.title,
              emoji: category.emoji,
              color: category.color,
              progress: progress,
              category: category.category
            };
          } catch (error) {
            console.error(`处理分类数据失败 (${category.category}):`, error);
            return {
              id: category.id.toString(),
              name: category.name || category.title,
              emoji: category.emoji,
              color: category.color,
              progress: 0,
              category: category.category
            };
          }
        });
        
        // 更新数据并设置缓存
        this.setData({
          wordbooks: updatedWordbooks,
          cachedWordbooksData: updatedWordbooks,
          cacheExpireTime: now + cacheDuration
        });
      } catch (error) {
        console.error('加载用户学习数据失败:', error);
        this._setDefaultData();
      }
    },
    
    // 设置默认数据
    _setDefaultData() {
      const defaultWordbooks = categoryConfig.map(category => ({
        id: category.id.toString(),
        name: category.name || category.title,
        emoji: category.emoji,
        color: category.color,
        progress: 0,
        category: category.category
      }));
      
      this.setData({
        wordbooks: defaultWordbooks
      });
    }
  }
})
